﻿/*****************************************
 * 
 *  copyright (c) by ylshen
 * 
 *  author : ylshen (syl.lucky@gmail.com)
 * 
 **************************************** */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using JYStockAnalyser.Face;
using JYStockAnalyser.Model;
using JYStockAnalyser.ClientLib;

namespace JYStockAnalyser.Manager
{
    public partial class FrmEstimateMethodManage : Form
    {
        EstimateRule m_currentRule;

        public FrmEstimateMethodManage()
        {
            InitializeComponent();
            this.dgStockCoefficients.AutoGenerateColumns = false;
        }

        private void FrmEstimateMethodManage_Load(object sender, EventArgs e)
        {
            m_init();
        }

        private void m_init()
        {
            if (!this.DesignMode) this.stockInputer1.BindData();
            m_loadPeirods();

            YearQuarter[] maxMinYears = ClientCache.Instance.MinAndMaxQuarter;

            for (int year = maxMinYears[0].Year; year <= maxMinYears[1].Year; year++)
            {
                for (int quarter = 1; quarter <= 4; quarter++)
                {
                    if (year == maxMinYears[0].Year && quarter < maxMinYears[0].Quarter)
                    { continue; }

                    if (year == maxMinYears[1].Year && quarter > maxMinYears[1].Quarter)
                    { break; }

                    this.cbNewBeginPeriod.Items.Add(new YearQuarter(year, quarter));
                    this.cbNewEndPeriod.Items.Add(new YearQuarter(year, quarter));
                }
            }

            foreach (string report in ClientCache.Instance.AllTypes.Keys)
            {
                this.cbReports.Items.Add(report);
            }
        }

        private void m_loadPeirods()
        {
            this.cbPeriods.Items.Clear();

            EstimateRuleManageFace face = new EstimateRuleManageFace();
            Dictionary<KeyValuePair<YearQuarter, YearQuarter>, int> periods = face.FindAllRuleYearQuarterAndIds();
            foreach (KeyValuePair<KeyValuePair<YearQuarter, YearQuarter>, int> period in periods)
            {
                Period per = new Period();
                if (period.Key.Key.Year == -1 && period.Key.Value.Year == -1)
                {
                    per.PeriodString = "默认";
                }
                else
                {
                    per.PeriodString = String.Format("{0} 至 {1}", period.Key.Key.GetTimeSimpleString(), period.Key.Value.GetTimeSimpleString());
                }
                per.RuleId = period.Value;
                this.cbPeriods.Items.Add(per);
            }
        }

        private void btnCreateNewPeriod_Click(object sender, EventArgs e)
        {
            if (this.cbNewBeginPeriod.SelectedIndex == -1)
            {
                Tool.ShowInformationBox("请输入起始日期");
                this.cbNewBeginPeriod.Focus();
                return;
            }
            if (this.cbNewEndPeriod.SelectedIndex == -1)
            {
                Tool.ShowInformationBox("请输入结束日期");
                this.cbNewEndPeriod.Focus();
                return;
            }

            YearQuarter beginQuarter = (YearQuarter)this.cbNewBeginPeriod.SelectedItem;
            YearQuarter endQuarter = (YearQuarter)this.cbNewEndPeriod.SelectedItem;

            if (beginQuarter.CompareTo(endQuarter) == 1)
            {
                Tool.ShowInformationBox("开始日期不能小于结束日期");
                this.cbNewBeginPeriod.Focus();
                return;
            }

            EstimateRuleManageFace face = new EstimateRuleManageFace();
            byte result = face.CreateNewRule(beginQuarter, endQuarter);
            switch (result)
            {
                case 1:
                    m_loadPeirods();
                    Tool.ShowInformationBox("创建成功!");
                    break;
                case 7:
                    Tool.ShowInformationBox("与其它规则的有效期限冲突");
                    break;
                case 110:
                    Tool.ShowInformationBox("创建失败!");
                    break;
            }
        }

        private void cbReports_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbReports.SelectedIndex != -1)
            {
                string report = (string)this.cbReports.SelectedItem;
                this.lbGuideLineTypes.Items.Clear();
                foreach (GuideLineType type in ClientCache.Instance.AllTypes[report][2])
                {
                    this.lbGuideLineTypes.Items.Add(type);
                }
            }
        }

        private void btnDeleteRule_Click(object sender, EventArgs e)
        {
            if (this.cbPeriods.SelectedIndex == -1) { return; }
            Period per = (Period)this.cbPeriods.SelectedItem;

            if (per.PeriodString.Equals("默认"))
            {
                Tool.ShowInformationBox("默认规则不能删除");
                return;
            }

            if (Tool.ShowQuestionBox("确认要删除此规则吗？删除后将无法恢复!") == DialogResult.Yes)
            {
                EstimateRuleManageFace face = new EstimateRuleManageFace();
                int result = face.DeleteRule(per.RuleId);
                switch (result)
                {
                    case 1:
                        m_loadPeirods();
                        Tool.ShowInformationBox("删除成功!");
                        break;
                    case 110:
                        Tool.ShowInformationBox("删除失败!");
                        break;
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string strSafetyA = this.txtSafetyA.Text.Trim();
            string strSafetyB = this.txtSafetyB.Text.Trim();
            string strSafetyC = this.txtSafetyC.Text.Trim();
            string strSafetyD = this.txtSafetyD.Text.Trim();
            string strSafetyE = this.txtSafetyE.Text.Trim();

            string strCommon1 = this.txtCommon1.Text.Trim();
            string strCommon2 = this.txtCommon2.Text.Trim();

            if (string.IsNullOrEmpty(strSafetyA))
            {
                Tool.ShowInformationBox("请输入系数!");
                this.txtSafetyA.Focus();
            }
            if (string.IsNullOrEmpty(strSafetyB))
            {
                Tool.ShowInformationBox("请输入系数!");
                this.txtSafetyB.Focus();
            }
            if (string.IsNullOrEmpty(strSafetyC))
            {
                Tool.ShowInformationBox("请输入系数!");
                this.txtSafetyC.Focus();
            }
            if (string.IsNullOrEmpty(strSafetyD))
            {
                Tool.ShowInformationBox("请输入系数!");
                this.txtSafetyD.Focus();
            }
            if (string.IsNullOrEmpty(strSafetyE))
            {
                Tool.ShowInformationBox("请输入系数!");
                this.txtSafetyE.Focus();
            }
            if (string.IsNullOrEmpty(strCommon1))
            {
                Tool.ShowInformationBox("请输入系数!");
                this.txtCommon1.Focus();
            }
            if (string.IsNullOrEmpty(strCommon2))
            {
                Tool.ShowInformationBox("请输入系数!");
                this.txtCommon2.Focus();
            }

            try
            {
                m_currentRule.ASafetyCoefficient = decimal.Parse(strSafetyA);
                m_currentRule.BSafetyCoefficient = decimal.Parse(strSafetyB);
                m_currentRule.CSafetyCoefficient = decimal.Parse(strSafetyC);
                m_currentRule.DSafetyCoefficient = decimal.Parse(strSafetyD);
                m_currentRule.ESafetyCoefficient = decimal.Parse(strSafetyE);

                m_currentRule.CommonCoefficients["溢价"] = decimal.Parse(strCommon1);
                m_currentRule.CommonCoefficients["行情"] = decimal.Parse(strCommon2);

                m_currentRule.GuideLineTypes.Clear();
                foreach (GuideLineType type in this.lbSelectedGuideLineTypes.Items)
                {
                    m_currentRule.GuideLineTypes.Add(type);
                }

                m_currentRule.TradeCoefficients.Clear();

                foreach (DataGridViewRow row in this.gvTrades.Rows)
                {
                    m_currentRule.TradeCoefficients.Add((string)row.Cells[0].Value, (decimal)row.Cells[1].Value);
                }

                m_currentRule.StockCoefficients.Clear();
                foreach (DataGridViewRow row in this.dgStockCoefficients.Rows)
                {
                    StockCoefficient coe = new StockCoefficient();
                    coe.StockNO = (string)row.Cells[0].Value;
                    coe.StockName = (string)row.Cells[1].Value;
                    coe.Coefficient = (decimal)row.Cells[2].Value;

                    m_currentRule.StockCoefficients.Add(coe);
                }

                EstimateRuleManageFace face = new EstimateRuleManageFace();
                byte result = face.UpdateRule(m_currentRule);
                switch (result)
                {
                    case 1:
                        Tool.ShowInformationBox("保存成功!");
                        break;
                    case 7:
                        Tool.ShowInformationBox("与其它规则的有效期限冲突");
                        break;
                    case 110:
                        Tool.ShowInformationBox("保存失败!");
                        break;
                }


                

              

            }
            catch (System.Exception err)
            {
                Tool.ShowInformationBox(err.ToString());

            }
        }

        private void cbPeriods_SelectedIndexChanged(object sender, EventArgs e)
        {
            m_clearInputs();

            if (this.cbPeriods.SelectedItem != null)
            {
                EstimateRuleManageFace face = new EstimateRuleManageFace();
                EstimateRule rule = face.GetRuleById(((Period)this.cbPeriods.SelectedItem).RuleId);
                m_currentRule = rule;
                foreach (GuideLineType type in rule.GuideLineTypes)
                {
                    this.lbSelectedGuideLineTypes.Items.Add(type);
                }
                this.txtSafetyA.Text = rule.ASafetyCoefficient.ToString();
                this.txtSafetyB.Text = rule.BSafetyCoefficient.ToString();
                this.txtSafetyC.Text = rule.CSafetyCoefficient.ToString();
                this.txtSafetyD.Text = rule.DSafetyCoefficient.ToString();
                this.txtSafetyE.Text = rule.ESafetyCoefficient.ToString();
                this.txtCommon1.Text = rule.CommonCoefficients["溢价"].ToString();
                this.txtCommon2.Text = rule.CommonCoefficients["行情"].ToString();

                List<TradeItem> items = new List<TradeItem>();
                foreach (KeyValuePair<string, decimal> item in rule.TradeCoefficients)
                {
                    TradeItem tradeItem = new TradeItem();
                    tradeItem.Trade = item.Key;
                    tradeItem.Value = item.Value;
                    items.Add(tradeItem);
                }

                this.gvTrades.DataSource = items;
                this.gvTrades.Columns[0].HeaderText = "行业";
                this.gvTrades.Columns[1].HeaderText = "系数";


                List<StockCoefficient> coes = new List<StockCoefficient>();
                coes.AddRange(rule.StockCoefficients);

                this.dgStockCoefficients.DataSource = coes;     

            }
            else
            {
                m_currentRule = null;
            }
        }

        private void m_clearInputs()
        {
            this.lbSelectedGuideLineTypes.Items.Clear();
            this.txtSafetyA.Text = string.Empty;
            this.txtSafetyB.Text = string.Empty;
            this.txtSafetyC.Text = string.Empty;
            this.txtSafetyD.Text = string.Empty;
            this.txtSafetyE.Text = string.Empty;
            this.txtCommon1.Text = string.Empty;
            this.txtCommon2.Text = string.Empty;
            this.gvTrades.DataSource = null;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (this.lbGuideLineTypes.SelectedItem != null)
            {
                if (!this.lbSelectedGuideLineTypes.Items.Contains(this.lbGuideLineTypes.SelectedItem))
                {
                    this.lbSelectedGuideLineTypes.Items.Add(this.lbGuideLineTypes.SelectedItem);
                }
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (this.lbSelectedGuideLineTypes.SelectedItem != null)
            {
                this.lbSelectedGuideLineTypes.Items.Remove(this.lbSelectedGuideLineTypes.SelectedItem);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAddStockCoe_Click(object sender, EventArgs e)
        {
            StockCoefficient coe = new StockCoefficient();
            coe.StockNO = this.stockInputer1.SelectedStockNO;
            coe.StockName = this.stockInputer1.SelectedStockName;
            coe.Coefficient = 1m;

            if (m_currentRule.StockCoefficients.Exists(new Predicate<StockCoefficient>(delegate(StockCoefficient coee)
                {
                    return coee.StockNO.Equals(coe.StockNO);
                })))
            {
                Tool.ShowInformationBox("此股票系数已存在");
                return;
            }


            List<StockCoefficient> coes = new List<StockCoefficient>();
            coes.AddRange(m_currentRule.StockCoefficients);
            coes.Add(coe);
            m_currentRule.StockCoefficients.Add(coe);

            this.dgStockCoefficients.DataSource = coes;     
        }        
    }

    public class Period
    {
        public string PeriodString;
        public int RuleId;

        public override string ToString()
        {
            return PeriodString;
        }
    }

    public class TradeItem
    {
        public string Trade { get; set; }
        public decimal Value { get; set; }
    }
}
